<template>
  <BasicModal
    v-bind="$attrs"
    :width="modalWidth"
    @register="registerModal"
    :title="getTitle"
    @ok="handleOK"
  >
    <BasicForm @register="registerForm">
      <template #filePath>
        <input type="file" @change="handleFileChange" />
      </template>
    </BasicForm>
    <template #centerFooter v-if="isUpdate">
      <Popconfirm :title="t('sys.configuration.IsDelete')" placement="left" @confirm="handleDelete">
        <a-button color="error">{{ t('sys.configuration.delete') }}</a-button>
      </Popconfirm>
    </template>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { message, Popconfirm } from 'ant-design-vue';
  import { addscriptAPI, addscriptTextAPI, deleteScriptAPI } from '@/api/demo/script'; // 假设你有一个添加接口
  import { accountFormSchema } from './account.data';
  import { useI18n } from '@/hooks/web/useI18n';

  const { t } = useI18n();
  defineOptions({ name: 'AccountModal' });
  const isUpdate = ref(true);
  const rowId = ref('');
  const modalWidth = ref('40%'); // 可以是像 600 这样的像素值，或者百分比 '50%'
  const emit = defineEmits(['success']);
  const file = ref<File | null>(null); // 用于存储文件
  const rowData = ref({});
  //注册表格数据
  const [registerForm, { resetFields, setFieldsValue, getFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: accountFormSchema,
    showActionButtonGroup: false,
  });
  //注册弹窗数据
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      rowData.value = data.record;
      rowId.value = data.record.id;
      setFieldsValue({
        ...data.record,
      });
    }
  });

  // 计算 title 的值
  const getTitle = computed(() =>
    !unref(isUpdate) ? t('sys.configuration.add') : t('sys.configuration.edit'),
  );

  async function handleOK() {
    await validate();
    const typeData = { ...getFieldsValue() };

    if (typeData.type == 'text') {
      const formData = new FormData();
      for (const key in typeData) {
        formData.append(key, typeData[key]);
      }
      let data = await addscriptTextAPI(formData);
      if (data.code == 200) {
        message.success(t('sys.configuration.succesSubmit'));
      }
      emit('success', data); // 触发 success 事件
      closeModal();
    } else {
      try {
        // 获取表单数据
        const formData = new FormData();
        const fieldsValue = getFieldsValue();

        // 添加其他表单字段
        for (const key in fieldsValue) {
          formData.append(key, fieldsValue[key]);
        }

        // 添加文件
        if (file.value) {
          formData.append('file', file.value);
        } else {
          message.error(t('sys.configuration.uploadfile'));
          return;
        }

        // 根据 isUpdate 的值决定调用哪个接口
        let data = await addscriptAPI(formData);
        if (data.code == 200) {
          message.success(t('sys.configuration.succesSubmit'));
        }
        emit('success', data); // 触发 success 事件
        closeModal();
      } finally {
        setModalProps({ confirmLoading: false });
      }
    }
  }

  function handleFileChange(event) {
    const selectedFile = event.target.files[0];
    if (selectedFile) {
      file.value = selectedFile; // 存储文件
    }
  }

  //删除文件
  async function handleDelete() {
    const data = await deleteScriptAPI(rowData.value);
    if (data.code == 200) {
      message.success(t('sys.configuration.deleteSucces'));
      emit('success', data); // 触发 success 事件
      closeModal();
    }
  }
</script>
